package File

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
)

func UploadFile(url string, filepath string) error {
	bodyBuf := &bytes.Buffer{}
	bodyWriter := multipart.NewWriter(bodyBuf)
	fileWriter, err := bodyWriter.CreateFormFile("uploadFile", filepath)
	if err != nil {
		return err
	}

	fh, err := os.Open(filepath)
	if err != nil {
		panic(err)
	}
	defer fh.Close()

	_, err = io.Copy(fileWriter, fh)
	contentType := bodyWriter.FormDataContentType()
	bodyWriter.Close()

	resp, err := http.Post(url, contentType, bodyBuf)
	if err != nil {
		return err
	}
	fmt.Println(resp.StatusCode, resp.Status)
	var body []byte
	_, err = resp.Body.Read(body)
	if err != nil {
		return err
	}
	fmt.Println(string(body))
	fmt.Println("==========================================================")
	return nil
}


func DownloadFile(url string, newFilePath string) error {
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	var data = make([]byte, 1024 * 4)
	var dataBuf = bytes.Buffer{}
	for {
		n, err := resp.Body.Read(data)
		if n > 0 {
			dataBuf.Write(data[:n])
		}
		if err != nil {
			break
		}
	}

	err = ioutil.WriteFile(newFilePath, dataBuf.Bytes(), os.ModePerm)
	if err != nil {
		return err
	}
	return nil
}
